% 对3D数据进行最大值投影

%  images path
DIR_path_LF_cell= ...
    { ...
    '/data8t/hryang/beads/20251103/SP/LFM/03_Reconstructed/'
    };

% list all lf images path
IMG_path_LF_cell={};
for i = 1:length(DIR_path_LF_cell)
    File_Path=DIR_path_LF_cell{i};
    File = dir(fullfile(File_Path,'*Z_1.tif'));
    IMG_path_LF_cell_i = cellfun(@(x) strcat(File_Path, x), {File.name}, 'UniformOutput',false);
    IMG_path_LF_cell_i = sort_nat(IMG_path_LF_cell_i);

    % make up output dir
    [pathstr,~,~]=fileparts(IMG_path_LF_cell_i{1});
    savePath = strrep(pathstr, '03_Reconstructed', '04_MIP');
    if exist(savePath)==7
        ;
    else
        mkdir(savePath);
    end

    IMG_path_LF_cell=[IMG_path_LF_cell IMG_path_LF_cell_i];
end

N=length(IMG_path_LF_cell);
Results=zeros(N,1);

% process one by one
for i = 1:N

    LF_im_name = IMG_path_LF_cell{i};
    disp(['frame: ' num2str(i) '/' num2str(length(IMG_path_LF_cell)) '  ' LF_im_name]);

    [~, base, ~] = fileparts(LF_im_name);

    % ===== 读取 3D 体数据 (Y,X,Z) =====
    V = loadtiff(LF_im_name);
    % 统一转换为 double 计算（如需保持原类型保存，后面再 cast 回来）
    Vd = double(V);

    % ===== 计算三向 MIP =====
    % XY：沿 Z 维取最大，输出 [Y X]
    M_XY = max(Vd, [], 3);

    % XZ：沿 Y 维取最大，得到 [X Z]，一般显示为 [Z X]，故转置
    % 这样行方向为 Z，列方向为 X，符合常见 XZ 视图直觉
    M_XZ = squeeze(max(Vd, [], 1))';   % [Z X]

    % YZ：沿 X 维取最大，得到 [Y Z]，同理转置为 [Z Y]
    M_YZ = squeeze(max(Vd, [], 2))';   % [Z Y]

    % ===== 按原数据类型保存 =====
    writetiff(M_XY, fullfile(savePath, [base '_XY.tif']),  max(M_XY(:)));
    writetiff(M_XZ, fullfile(savePath, [base '_XZ.tif']),  max(M_XZ(:)));
    writetiff(M_YZ, fullfile(savePath, [base '_YZ.tif']),  max(M_YZ(:)));
end

fprintf('完成：共处理 %d 个 3D TIFF，结果已保存到：%s\n', N, savePath);
